
import { ref, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getNormalPath } from '@/utils/ruoyi'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
import useTagsViewStore from '@/store/modules/tagsView'

export const moveToViewHandler = () => {
    const route = useRoute();
    const router = useRouter();
    const routes = computed(() => usePermissionStore().routes);
    const theme = computed(() => useSettingsStore().theme);
    const visitedViews = computed(() => useTagsViewStore().visitedViews);
    const visible = ref(false);
    const top = ref(0);
    const left = ref(0);
    const selectedTag = ref({});
    const affixTags = ref([]);
    const { proxy } = getCurrentInstance();

    function isActive(r) {
        return r.path === route.path
    }
    function activeStyle(tag) {
        if (!isActive(tag)) return {};
        return {
            "background-color": theme.value,
            "border-color": theme.value
        };
    }
    function isAffix(tag) {
        return tag.meta && tag.meta.affix
    }
    function isFirstView() {
        try {
            return selectedTag.value.fullPath === '/index' || selectedTag.value.fullPath === visitedViews.value[1].fullPath
        } catch (err) {
            return false
        }
    }
    function isLastView() {
        try {
            return selectedTag.value.fullPath === visitedViews.value[visitedViews.value.length - 1].fullPath
        } catch (err) {
            return false
        }
    }
    function filterAffixTags(routes, basePath = '') {
        let tags = []
        routes.forEach(route => {
            if (route.meta && route.meta.affix) {
                const tagPath = getNormalPath(basePath + '/' + route.path)
                tags.push({
                    fullPath: tagPath,
                    path: tagPath,
                    name: route.name,
                    meta: { ...route.meta }
                })
            }
            if (route.children) {
                const tempTags = filterAffixTags(route.children, route.path)
                if (tempTags.length >= 1) {
                    tags = [...tags, ...tempTags]
                }
            }
        })
        return tags
    }
    function initTags() {
        const res = filterAffixTags(routes.value);
        affixTags.value = res;
        for (const tag of res) {
            // Must have tag name
            if (tag.name) {
                useTagsViewStore().addVisitedView(tag)
            }
        }
    }
    function addTags() {
        const { name } = route
        if (name) {
            useTagsViewStore().addView(route)
            if (route.meta.link) {
                useTagsViewStore().addIframeView(route);
            }
        }
        return false
    }
    function refreshSelectedTag(view) {
        proxy.$tab.refreshPage(view);
        if (route.meta.link) {
            useTagsViewStore().delIframeView(route);
        }
    }
    function closeSelectedTag(view) {
        proxy.$tab.closePage(view).then(({ visitedViews }) => {
            if (isActive(view)) {
                toLastView(visitedViews, view)
            }
        })
    }
    function closeRightTags() {
        proxy.$tab.closeRightPage(selectedTag.value).then(visitedViews => {
            if (!visitedViews.find(i => i.fullPath === route.fullPath)) {
                toLastView(visitedViews)
            }
        })
    }
    function closeLeftTags() {
        proxy.$tab.closeLeftPage(selectedTag.value).then(visitedViews => {
            if (!visitedViews.find(i => i.fullPath === route.fullPath)) {
                toLastView(visitedViews)
            }
        })
    }
    function closeAllTags(view) {
        proxy.$tab.closeAllPage().then(({ visitedViews }) => {
            if (affixTags.value.some(tag => tag.path === route.path)) {
                return
            }
            toLastView(visitedViews, view)
        })
    }
    function toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
            router.push(latestView.fullPath)
        } else {
            if (view.name === 'Dashboard') {
                // to reload home page
                router.replace({ path: '/redirect' + view.fullPath })
            } else {
                router.push('/')
            }
        }
    }
    function openMenu(tag, e) {
        const menuMinWidth = 105
        const offsetLeft = proxy.$el.getBoundingClientRect().left // container margin left
        const offsetWidth = proxy.$el.offsetWidth // container width
        const maxLeft = offsetWidth - menuMinWidth // left boundary
        const l = e.clientX - offsetLeft + 15 // 15: margin right

        if (l > maxLeft) {
            left.value = maxLeft
        } else {
            left.value = l
        }

        top.value = e.clientY
        visible.value = true
        selectedTag.value = tag
    }
    function closeMenu() {
        visible.value = false
    }
    function handleScroll() {
        closeMenu()
    }
    return {
        left,
        top,
        addTags,
        closeLeftTags,
        closeRightTags,
        closeMenu, openMenu,
        initTags, activeStyle,
        closeSelectedTag,
        refreshSelectedTag, visible, visitedViews,
        closeAllTags, isActive, selectedTag,
        isLastView, isFirstView, isAffix, handleScroll
    };
};

